#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <ctype.h>
#include <time.h>
#include "thread1.h"
#include "msg_queue.h"
#include "log_utils.h"

#define CONFIG_FILE "device_config.txt"
#define MAX_CMD_LEN 256
#define MAX_WIFI_NAME_LEN 64
#define MAX_WIFI_PASS_LEN 64
#define MAX_IP_ADDR_LEN 20
#define CHECK_INTERVAL 30  // 检查WiFi状态的间隔（秒）
#define MAX_SCAN_RETRIES 10  // 最大扫描重试次数

// 连接状态返回值
#define WIFI_STATUS_NORMAL 0
#define WIFI_STATUS_ERROR  1

// 全局变量，表示WiFi连接状态
int g_wifi_connection_status = WIFI_CONNECTION_FAILURE;

// 执行命令并返回状态码
static int execute_cmd(const char *cmd) {
    LOG_DEBUG(LOG_TO_FILE, LOG_MODULE_WIFI, "执行命令: %s", cmd);
    int ret = system(cmd);
    LOG_DEBUG(LOG_TO_FILE, LOG_MODULE_WIFI, "命令执行结果: %d", ret);
    return ret;
}

// 执行命令并获取输出
static int execute_cmd_with_output(const char *command, char *output, size_t output_size) {
    FILE *fp;
    char buffer[256];
    
    if (command == NULL || output == NULL || output_size == 0) {
        return -1;
    }
    
    // 清空输出缓冲区
    output[0] = '\0';
    
    // 执行命令
    fp = popen(command, "r");
    if (fp == NULL) {
        return -1;
    }
    
    // 读取命令输出
    while (fgets(buffer, sizeof(buffer), fp) != NULL) {
        if (strlen(output) + strlen(buffer) < output_size) {
            strcat(output, buffer);
        }
    }
    
    int ret = pclose(fp);
    LOG_DEBUG(LOG_TO_FILE, LOG_MODULE_WIFI, "命令结果:\n%s", output);
    LOG_DEBUG(LOG_TO_FILE, LOG_MODULE_WIFI, "命令返回值: %d", ret);
    
    return ret;
}

// 从配置文件中获取WiFi配置信息
static int get_wifi_config(char *target_wifi_name, char *target_wifi_pass, char *assigned_ip, 
                          int name_max_len, int pass_max_len, int ip_max_len) {
    FILE *fp;
    char line[512];
    char *ptr, *value;
    int name_found = 0;
    int pass_found = 0;
    int ip_found = 0;
    int mode_correct = 0;
    
    fp = fopen(CONFIG_FILE, "r");
    if (fp == NULL) {
        LOG_ERROR(LOG_TO_FILE, LOG_MODULE_WIFI, "无法打开配置文件 %s", CONFIG_FILE);
        return -1;
    }
    
    // 默认值
    strncpy(target_wifi_name, "LDCICM_Router", name_max_len - 1);
    target_wifi_name[name_max_len - 1] = '\0';
    
    strncpy(target_wifi_pass, "hitmc401", pass_max_len - 1);
    target_wifi_pass[pass_max_len - 1] = '\0';
    
    strncpy(assigned_ip, "192.168.1.1", ip_max_len - 1);
    assigned_ip[ip_max_len - 1] = '\0';
    
    while (fgets(line, sizeof(line), fp)) {
        // 检查WiFi模式是否为终端模式
        ptr = strstr(line, "\"wifi_mode\"");
        if (ptr && !mode_correct) {
            ptr = strchr(ptr + 10, ':');
            if (ptr) {
                ptr++;
                while (isspace(*ptr)) ptr++;
                
                if (*ptr == '"') {
                    value = ++ptr;
                    ptr = strchr(value, '"');
                    if (ptr) {
                        *ptr = '\0';
                        if (strcmp(value, "terminal") == 0) {
                            mode_correct = 1;
                            LOG_INFO(LOG_TO_FILE, LOG_MODULE_WIFI, "设备配置为终端模式");
                        }
                    }
                }
            }
        }
        
        // 查找目标WiFi名称
        ptr = strstr(line, "\"target_wifi_name\"");
        if (ptr && !name_found) {
            ptr = strchr(ptr + 17, ':');
            if (ptr) {
                ptr++;
                while (isspace(*ptr)) ptr++;
                
                if (*ptr == '"') {
                    value = ++ptr;
                    ptr = strchr(value, '"');
                    if (ptr) {
                        *ptr = '\0';
                        strncpy(target_wifi_name, value, name_max_len - 1);
                        target_wifi_name[name_max_len - 1] = '\0';
                        name_found = 1;
                    }
                }
            }
        }
        
        // 查找目标WiFi密码
        ptr = strstr(line, "\"target_wifi_password\"");
        if (ptr && !pass_found) {
            ptr = strchr(ptr + 21, ':');
            if (ptr) {
                ptr++;
                while (isspace(*ptr)) ptr++;
                
                if (*ptr == '"') {
                    value = ++ptr;
                    ptr = strchr(value, '"');
                    if (ptr) {
                        *ptr = '\0';
                        strncpy(target_wifi_pass, value, pass_max_len - 1);
                        target_wifi_pass[pass_max_len - 1] = '\0';
                        pass_found = 1;
                    }
                }
            }
        }
        
        // 查找分配的IP地址
        ptr = strstr(line, "\"assigned_ip\"");
        if (ptr && !ip_found) {
            ptr = strchr(ptr + 12, ':');
            if (ptr) {
                ptr++;
                while (isspace(*ptr)) ptr++;
                
                if (*ptr == '"') {
                    value = ++ptr;
                    ptr = strchr(value, '"');
                    if (ptr) {
                        *ptr = '\0';
                        strncpy(assigned_ip, value, ip_max_len - 1);
                        assigned_ip[ip_max_len - 1] = '\0';
                        ip_found = 1;
                    }
                }
            }
        }
        
        // 如果都找到了，就可以退出循环
        if (mode_correct && name_found && pass_found && ip_found) {
            break;
        }
    }
    
    fclose(fp);
    
    // 确认是终端模式
    if (!mode_correct) {
        LOG_WARN(LOG_TO_FILE, LOG_MODULE_WIFI, "设备不是终端模式，无法连接WiFi");
        return -1;
    }
    
    return 0;
}

/**
 * 功能块1: 连接WiFi路由器
 * 
 * 1. 禁用WiFi功能，等待3秒
 * 2. 使能WiFi功能，等待3秒
 * 3. 扫描WiFi网络，查找目标WiFi
 * 4. 连接到目标WiFi
 * 
 * 返回值: 0表示成功连接，-1表示失败
 */
static int connect_to_wifi_router(void) {
    char target_wifi_name[MAX_WIFI_NAME_LEN] = {0};
    char target_wifi_pass[MAX_WIFI_PASS_LEN] = {0};
    char assigned_ip[MAX_IP_ADDR_LEN] = {0};
    char scan_output[4096];
    char cmd[MAX_CMD_LEN];
    int found = 0;
    int retry_count = 0;
    char msg_buffer[128];
    
    LOG_INFO(LOG_TO_FILE, LOG_MODULE_WIFI, "开始WiFi连接过程...");
    
    // 从配置文件读取WiFi配置
    if (get_wifi_config(target_wifi_name, target_wifi_pass, assigned_ip,
                      sizeof(target_wifi_name), sizeof(target_wifi_pass), sizeof(assigned_ip)) != 0) {
        LOG_WARN(LOG_TO_FILE, LOG_MODULE_WIFI, "读取WiFi配置失败，使用默认值");
    }
    
    LOG_INFO(LOG_TO_FILE, LOG_MODULE_WIFI, "目标WiFi名称: %s", target_wifi_name);
    LOG_DEBUG(LOG_TO_FILE, LOG_MODULE_WIFI, "目标WiFi密码: %s", target_wifi_pass);
    LOG_INFO(LOG_TO_FILE, LOG_MODULE_WIFI, "目标IP地址: %s", assigned_ip);
    
    // 1. 先禁用WiFi功能
    LOG_INFO(LOG_TO_FILE, LOG_MODULE_WIFI, "禁用WiFi功能...");
    execute_cmd("nmcli radio wifi off");
    sleep(3);
    
    // 2. 使能WiFi功能
    LOG_INFO(LOG_TO_FILE, LOG_MODULE_WIFI, "使能WiFi功能...");
    execute_cmd("nmcli radio wifi on");
    sleep(3);
    
    // 3. 循环扫描WiFi网络，直到找到目标WiFi或达到最大重试次数
    while (!found && retry_count < MAX_SCAN_RETRIES) {
        LOG_INFO(LOG_TO_FILE, LOG_MODULE_WIFI, "扫描WiFi网络 (尝试 %d/%d)...", retry_count + 1, MAX_SCAN_RETRIES);
        
        // 强制刷新WiFi扫描结果
        if (retry_count > 0 && retry_count % 3 == 0) {
            LOG_DEBUG(LOG_TO_FILE, LOG_MODULE_WIFI, "强制刷新WiFi扫描结果...");
            execute_cmd("nmcli device wifi rescan");
            sleep(2);  // 给点时间让扫描完成
        }
        
        if (execute_cmd_with_output("nmcli device wifi", scan_output, sizeof(scan_output)) != 0) {
            LOG_WARN(LOG_TO_FILE, LOG_MODULE_WIFI, "扫描WiFi失败，重试...");
            retry_count++;
            sleep(1);
            continue;
        }
        
        // 检查是否找到目标WiFi
        if (strstr(scan_output, target_wifi_name) != NULL) {
            LOG_INFO(LOG_TO_FILE, LOG_MODULE_WIFI, "找到目标WiFi: %s", target_wifi_name);
            found = 1;
        } else {
            LOG_DEBUG(LOG_TO_FILE, LOG_MODULE_WIFI, "未找到目标WiFi: %s，等待1秒后重新扫描", target_wifi_name);
            retry_count++;
            sleep(1);
        }
    }
    
    // 如果达到最大重试次数仍未找到目标WiFi，返回失败
    if (!found) {
        LOG_ERROR(LOG_TO_FILE, LOG_MODULE_WIFI, "在%d次尝试后未找到目标WiFi，连接失败", MAX_SCAN_RETRIES);
        g_wifi_connection_status = WIFI_CONNECTION_FAILURE;
        return -1;
    }
    
    // 4. 连接到目标WiFi
    LOG_INFO(LOG_TO_FILE, LOG_MODULE_WIFI, "尝试连接到WiFi: %s", target_wifi_name);
    snprintf(cmd, sizeof(cmd), "nmcli device wifi connect \"%s\" password %s ifname wlan0", 
             target_wifi_name, target_wifi_pass);
    
    if (execute_cmd(cmd) != 0) {
        LOG_ERROR(LOG_TO_FILE, LOG_MODULE_WIFI, "连接到WiFi失败");
        g_wifi_connection_status = WIFI_CONNECTION_FAILURE;
        return -1;
    }
    
    // 等待连接建立
    sleep(2);
    
    // 检查连接是否成功
    if (execute_cmd_with_output("nmcli connection show --active", scan_output, sizeof(scan_output)) == 0 &&
        strstr(scan_output, target_wifi_name) != NULL) {
        LOG_INFO(LOG_TO_FILE, LOG_MODULE_WIFI, "成功连接到WiFi: %s", target_wifi_name);
        
        // 设置全局状态
        g_wifi_connection_status = WIFI_CONNECTION_SUCCESS;
        
        // 发送消息到消息队列
        if (g_msg_queue_id >= 0) {
            snprintf(msg_buffer, sizeof(msg_buffer), 
                    "WiFi连接已建立，SSID: %s，时间: %ld", 
                    target_wifi_name, time(NULL));
            
            if (send_msg(g_msg_queue_id, MSG_TYPE_WIFI_RESET, msg_buffer) == 0) {
                LOG_DEBUG(LOG_TO_FILE, LOG_MODULE_WIFI, "已发送WiFi连接消息到消息队列");
            }
        }
        
        return 0;  // 连接成功
    } else {
        LOG_ERROR(LOG_TO_FILE, LOG_MODULE_WIFI, "连接后检查失败，WiFi连接未成功建立");
        g_wifi_connection_status = WIFI_CONNECTION_FAILURE;
        return -1;  // 连接失败
    }
}

/**
 * 功能块2: 检查WiFi连接状态
 * 
 * 检查当前WiFi连接是否正常
 * 
 * 返回值: WIFI_STATUS_NORMAL表示连接正常，WIFI_STATUS_ERROR表示连接异常
 */
static int check_wifi_connection_status(void) {
    char output[4096];
    char target_wifi_name[MAX_WIFI_NAME_LEN] = {0};
    char target_wifi_pass[MAX_WIFI_PASS_LEN] = {0};
    char assigned_ip[MAX_IP_ADDR_LEN] = {0};
    
    // 从配置文件读取WiFi配置信息（含IP地址）
    if (get_wifi_config(target_wifi_name, target_wifi_pass, assigned_ip,
                      sizeof(target_wifi_name), sizeof(target_wifi_pass), sizeof(assigned_ip)) != 0) {
        LOG_WARN(LOG_TO_FILE, LOG_MODULE_WIFI, "读取WiFi配置失败，使用默认值");
    }
    
    LOG_DEBUG(LOG_TO_FILE, LOG_MODULE_WIFI, "检查WiFi连接状态...");
    
    // 检查WiFi功能是否启用
    if (execute_cmd_with_output("nmcli radio wifi", output, sizeof(output)) != 0 || 
        strstr(output, "enabled") == NULL) {
        LOG_WARN(LOG_TO_FILE, LOG_MODULE_WIFI, "WiFi功能未启用");
        g_wifi_connection_status = WIFI_CONNECTION_FAILURE;
        return WIFI_STATUS_ERROR;
    }
    
    // 检查WiFi是否已连接到目标网络
    if (execute_cmd_with_output("nmcli connection show --active", output, sizeof(output)) != 0 || 
        strstr(output, target_wifi_name) == NULL) {
        LOG_WARN(LOG_TO_FILE, LOG_MODULE_WIFI, "WiFi未连接到目标网络: %s", target_wifi_name);
        g_wifi_connection_status = WIFI_CONNECTION_FAILURE;
        return WIFI_STATUS_ERROR;
    }
    
    // 使用配置文件中的assigned_ip进行ping测试，检查连接性
    LOG_DEBUG(LOG_TO_FILE, LOG_MODULE_WIFI, "使用配置文件中的IP地址进行连通性测试: %s", assigned_ip);
    char ping_cmd[64];
    snprintf(ping_cmd, sizeof(ping_cmd), "ping -c 1 -W 2 %s", assigned_ip);
    if (execute_cmd(ping_cmd) != 0) {
        LOG_WARN(LOG_TO_FILE, LOG_MODULE_WIFI, "无法ping通目标IP: %s", assigned_ip);
        g_wifi_connection_status = WIFI_CONNECTION_FAILURE;
        return WIFI_STATUS_ERROR;
    }
    
    // 所有检查都通过，连接正常
    LOG_INFO(LOG_TO_FILE, LOG_MODULE_WIFI, "WiFi连接正常");
    g_wifi_connection_status = WIFI_CONNECTION_SUCCESS;
    return WIFI_STATUS_NORMAL;
}

// 线程1函数实现 - WiFi终端连接管理
void *thread1_function(void *arg) {
    (void)arg;  // 标记参数为未使用
    int ret;
    
    LOG_INFO(LOG_TO_FILE, LOG_MODULE_WIFI, "线程1: WiFi终端连接管理启动");
    
    // 第一次连接WiFi
    LOG_INFO(LOG_TO_FILE, LOG_MODULE_WIFI, "初始化WiFi连接...");
    ret = connect_to_wifi_router();
    if (ret != 0) {
        LOG_WARN(LOG_TO_FILE, LOG_MODULE_WIFI, "初始化WiFi连接失败，将在主循环中重试");
    } else {
        LOG_INFO(LOG_TO_FILE, LOG_MODULE_WIFI, "初始化WiFi连接成功");
    }
    
    // 主循环：监控WiFi连接状态
    while (1) {
        // 检查WiFi连接状态
        ret = check_wifi_connection_status();
        
        // 如果连接异常，尝试重新连接
        if (ret == WIFI_STATUS_ERROR) {
            LOG_WARN(LOG_TO_FILE, LOG_MODULE_WIFI, "检测到WiFi连接异常，尝试重新连接...");
            connect_to_wifi_router();
        }
        
        // 等待一段时间后再次检查
        sleep(CHECK_INTERVAL);
    }
    
    return NULL;
} 